import axios from 'axios'

import {Message} from 'element-ui'
import store from "@/store";
const Timeout=3600//定义超时时间
import {getTimestamp} from '@/utils/auth'
import router from "@/router";



//引入消息提示
//实例化一个axios
const server=axios.create({
baseURL:process.env.VUE_APP_BASE_API,
timeout:5000
})

//================请求拦截器
server.interceptors.request.use(config=>{
//在这个位置统一注入token，发送给服务器
  if (store.getters.token){
    if (ischaoshi()){
      store.dispatch('user/logout')
      router.push('/login')
      return  Promise.reject(new Error('token超时了'))
    }
    config.headers['Authorization']=`Bearer ${store.getters.token}`//携带token
  }
  return config//必须返回
},error => {
  return Promise.reject(error)
})


//================响应拦截器
server.interceptors.response.use(response=>{
// axios 默认加了一层data
const{success,message,data}=response.data
  if (success){
    return data
  }else {
   Message.error( message)
    return  Promise.reject(new Error(message))
  }

},error => {
  Message.error(error.message) /*显示消息错误*/
  return Promise.reject(error) /*返货错误，让执行链跳出成功，直接进入catch*/

})
 function ischaoshi(){
  var  currenttime=Date.now()
   var timestamp=getTimestamp()
 return  (currenttime-timestamp) / 1000 > Timeout
 }

//导出模块
export default  server

